<!--
 * @Description: 
 * @Version: 
 * @Autor: LiChuang
 * @Date: 2023-11-16 15:01:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-11-23 19:37:52
-->
<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute top-0 flex items-center justify-end px-5 h-20 w-full">
      <el-switch
        v-model="isDark"
        inline-prompt
        :active-icon="IconEpMoon"
        :inactive-icon="IconEpSunny"
        active-color="var(--el-fill-color-dark)"
        inactive-color="var(--el-color-primary)"
        @change="handleThemeChange"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <div class="main">
      <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
        <div class="title">
          {{$t('navbar.title')}}
        </div>
        <el-form-item prop="username">
          <div class="p-2">
            <svg-icon icon-class="user" />
          </div>
          <el-input ref="username" v-model="loginData.phone" class="flex-1" size="large"
            :placeholder="$t('login.username')" name="phone" />
        </el-form-item>

        <el-tooltip :disabled="isCapslock === false" content="点击查看密码" placement="right">
          <el-form-item prop="password">
            <span class="p-2">
              <svg-icon icon-class="password" />
            </span>
            <el-input v-model="loginData.password" class="flex-1" :placeholder="$t('login.password')"
              :type="passwordVisible === false ? 'password' : 'input'" size="large" name="password" @keyup="checkCapslock"
              @keyup.enter="handleLogin" />
            <span class="mr-2" @click="passwordVisible = !passwordVisible">
              <svg-icon :icon-class="passwordVisible === false ? 'eye' : 'eye-open'" class="cursor-pointer" />
            </span>
          </el-form-item>
        </el-tooltip>
        <el-button :loading="loading" type="primary" class="w-full" @click.prevent="handleLogin">{{ $t("login.login") }}
        </el-button>
      </el-form>
    </div>

  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import router from "@/router";
import LangSelect from "@/components/LangSelect/index.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import IconEpSunny from "~icons/ep/sunny";
import IconEpMoon from "~icons/ep/moon";
import { useSettingsStore } from "@/store/modules/settings";

// 状态管理依赖
import { useUserStore } from "@/store/modules/user";
import { useAppStore } from "@/store/modules/app";

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import defaultSettings from "@/settings";

/**
 * 明亮/暗黑主题切换
 */
const settingsStore = useSettingsStore();
const isDark = ref<boolean>(settingsStore.theme === "dark");
const handleThemeChange = (isDark: any) => {
  useToggle(isDark);
  settingsStore.changeSetting({
    key: "theme",
    value: isDark ? "dark" : "light",
  });
};

/**
 * 根据屏幕宽度切换设备模式
 */
const appStore = useAppStore();
const WIDTH = 992; // 响应式布局容器固定宽度  大屏（>=1200px） 中屏（>=992px） 小屏（>=768px）
const { width } = useWindowSize();
watchEffect(() => {
  if (width.value < WIDTH) {
    appStore.toggleDevice("mobile");
  } else {
    appStore.toggleDevice("desktop");
  }
});

const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const passwordVisible = ref(false); // 密码是否可见
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref

const loginData = ref<LoginData>({
  phone: "",
  password: "",
});

const { t } = useI18n();
const loginRules = computed(() => {
  const prefix = appStore.language === "en" ? "Please enter " : "请输入";
  return {
    phone: [
      {
        required: true,
        trigger: "blur",
        message: `${prefix}${t("login.username")}`,
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        validator: (rule: any, value: any, callback: any) => {
          if (value.length < 6) {
            callback(new Error("The password can not be less than 6 digits"));
          } else {
            callback();
          }
        },
        message: `${prefix}${t("login.password")}`,
      },
    ]
  };
});

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e;
  isCapslock.value = key && key.length === 1 && key >= "A" && key <= "Z";
}



/**
 * 登录
 */
const route = useRoute();
const userStore = useUserStore();
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;

          const redirect = (query.redirect as LocationQueryValue) ?? "/";

          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );

          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

onMounted(() => {
  // 主题初始化
  const theme = useSettingsStore().theme;
  useSettingsStore().changeSetting({ key: "theme", value: theme });
  if (theme == "dark") {
    document.documentElement.classList.add("dark");
  } else {
    document.documentElement.classList.remove("dark");
  }
});
</script>

<style lang="scss" scoped>
.login-container {
  @apply w-full h-full flex-center;
  background: linear-gradient(129deg, #E0F8F4, #C7FFF6, #BBE4FE, #289FE3, #4249E0);
  overflow-y: auto;

  .main {
    width: 1336px;
    height: 700px;
    background: url("@/assets/images/bg.png") no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .login-form {
    position: relative;
    right: 170px;
    width: 420px;

    .title {
      font-size: 42px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #333333;
      padding-bottom: 80px; 
      background: linear-gradient(0deg, #354859 0%, #728290 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  .el-button{
    width: 420px;
    height: 60px;
    background: #2690FD;
    box-shadow: 0px 0px 18px 0px rgba(56,102,206,0.43);
    border-radius: 30px;
    margin-top: 60px;
  }
    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: right;
        width: 100%;
        height: 100%;
        font-size: 18px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);

        svg {
          margin-right: 10px;
        }
      }
    }
  }
}

.el-form-item {
  background: #F1F6F9;
  border-radius: 55px;
  margin-bottom: 40px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s;
      /* 通过延时渲染背景色变相去除背景颜色 */
    }
  }
}
</style>
